package com.terry.gametest.test.aspect;

import com.terry.gametest.test.annotation.LogAndCache;
import com.terry.gametest.test.util.SpelParser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Slf4j
@Aspect
@Component
public class LogAndCacheAspect {

    @Autowired
    CacheManager cacheManager;

    @Around("@annotation(logAndCache)")

    public Object doAround(ProceedingJoinPoint point, LogAndCache logAndCache) throws Throwable{
//        cacheManager.getCache(logAndCache.cacheName(),point.getArgs()[1]);
//        cacheManager
        String key = logAndCache.key();
        String cacheKey = extraKey(key,point);
        String cacheName = logAndCache.cacheName();
        boolean needLog = logAndCache.needLog();
        Object ret = point.proceed();
        System.out.println();
        return ret ;
    }

    public String extraKey(String key,ProceedingJoinPoint point){
        Method method = ((MethodSignature)point.getSignature()).getMethod();
        Parameter[] parameters = method.getParameters();
        String[] parameterNames = new String[parameters.length];
        for (int i=0;i<parameters.length;i++){
            parameterNames[i] = parameters[i].getName();
        }
        return SpelParser.extraKey(key,parameterNames,point.getArgs());
    }
}
